//
//  Status.swift
//  WEIBO_SWIFT
//
//  Created by 岳挺 on 15/7/1.
//  Copyright © 2015年 yueting. All rights reserved.
//

import UIKit
import SDWebImage

let home_webo_baseURL = "2/statuses/home_timeline.json"

class Status: NSObject {
    
    //微博创建时间
    var created_at : String?
    //微博ID
    var id : Int = 0
    //微博信息内容
    var text : String?
    //微博配图
    var pic_urls : [[String : String]]?{
        didSet{
            imageURL = [NSURL]()
            for dict in pic_urls! {
                let picStr = dict["thumbnail_pic"]!
                imageURL!.append(NSURL(string: picStr)!)
            }
        }
    }
    //用户配图URL
    private var imageURL : [NSURL]?
    //计算属性，配图的URL数组，如果转发微博有图片则缓存转发微博的url数组，如果原创微博有配图，则缓存原创微博的配图
    var picURL : [NSURL]?{
        return retweeted_status == nil ? imageURL : retweeted_status?.imageURL
    }
    //用户
    var user : User?
    //微博来源
    var source : String?
    //转发微博
    var retweeted_status : Status?
    //属性数组
    static let propertiesArr = ["created_at","id","text","pic_urls","retweeted_status","user"]
    
    init(dict : [String : AnyObject]) {
        super.init()
        
        for key in Status.propertiesArr {
            if dict[key] == nil || key == "user" || key == "retweeted_status" {
                continue
            }
            setValue(dict[key], forKey: key)
        }
        if let u = dict["user"]{
            user = User(dict: u as! [String : AnyObject])
        }
        
        if let r = dict["retweeted_status"] {
            retweeted_status = Status(dict: r as! [String : AnyObject])
        }
    }
    
    class func statusArray (array : [[String : AnyObject]]) ->[Status] {
        var arrM = [Status]()
        for dict in array {
            arrM.append(Status.statusWithDict(dict))
        }
        return arrM
    }
    
    class func statusWithDict (dict : [String : AnyObject]) -> Status{
        return Status(dict: dict)
    }
    
    ///  加载数据
    /**
    since_id    若指定此参数，则返回ID比since_id大的微博（即比since_id时间晚的微博），默认为0
    max_id      若指定此参数，则返回ID小于或等于max_id的微博，默认为0
    */
    class func loadData(since_id : Int, max_id : Int, finished : (statuses : [Status]? , error : NSError? ) ->()){
        var param = ["access_token" : sharedUserAccount!.access_token]
        
        if since_id > 0 {
            param["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            param["since_id"] = "0"
            param["max_id"] = "\(max_id - 1)"
        }
        
        NetWorkTool.sharedNetWorkTool().GET(home_webo_baseURL, parameters: param, success: { (_, json) -> Void in
            
            //从获取的网络数据中拿到微博的字典数组
            if let statusArr = json["statuses"] as? [[String : AnyObject]]{
                
                //获得微博模型数组
                let list = statusArray(statusArr)
                
                //加载每个模型数组的图片
                weiboImageCache(list, finish: finished)
            }
            // 
            finished(statuses: nil, error: nil)
            
            }) { (_, error) -> Void in
                print(error)
                finished(statuses: nil, error: error)
        }
    }
    
    class func weiboImageCache (status : [Status] , finish : (statuses : [Status]? , error : NSError? ) -> ()) {
        //定义调度组
        let group = dispatch_group_create()
        
        //遍历微博数组，缓存图片
        for s in status {
            //判断微博中的url是否存在
            if s.picURL == nil || s.picURL!.isEmpty {
                continue
            }
            
            for url in s.picURL! {
                
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, error:NSError?, _, _, _) -> Void in
                    print("----------------\(error)")
//                    print(NSHomeDirectory())
                    dispatch_group_leave(group)
                })
            }
        }
        
        //监听群组调度执行
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
        //完成回调
        finish(statuses: status, error: nil)
        }
    }
    
    override var description : String {
        let dict = dictionaryWithValuesForKeys(Status.propertiesArr)
        return "\(dict)"
    }

}
